package com.example.waterdispenserm2.mo.inductioncong;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.waterdispenserm2.R;
import com.example.waterdispenserm2.base.BasicsActivity;
import com.example.waterdispenserm2.databinding.ActivitySerialCookerDisplayBinding;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class SerialCookerDisplayActivity extends BasicsActivity<ActivitySerialCookerDisplayBinding> implements InductionCookerSerialSlave.ProtocolCallback{

    private InductionCookerSerialSlave protocol;
    private ImageView[] leds = new ImageView[8];
    @Override
    public void widgetClick(View v) {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initView() {
        // 初始化UI组件
        initUI();

        // 初始化协议处理器
        protocol = new InductionCookerSerialSlave(this, this);
    }

    @Override
    protected ActivitySerialCookerDisplayBinding getViewBinding() {
        return ActivitySerialCookerDisplayBinding.inflate(LayoutInflater.from(this));
    }

    private void initUI() {
        // 初始化LED视图
        leds[0] = findViewById(R.id.led_frying);
        leds[1] = findViewById(R.id.led_porridge);
        leds[2] = findViewById(R.id.led_hotpot);
        leds[3] = findViewById(R.id.led_high_fire);
        leds[4] = findViewById(R.id.led_low_fire);
        leds[5] = findViewById(R.id.led_boil_water);
        leds[6] = findViewById(R.id.led_steam);
        leds[7] = findViewById(R.id.led_stew);

        // 串口选择逻辑
        binding.btOpen.setOnClickListener(v -> {
            String input = binding.etAdd.getText().toString().trim();
            String path = "/dev/ttyS0"; // 默认路径

            if (!TextUtils.isEmpty(input)) {
                switch (input) {
                    case "0": path = "/dev/ttyS0"; break;
                    case "1": path = "/dev/ttyS1"; break;
                    case "2": path = "/dev/ttyS2"; break;
                    case "3": path = "/dev/ttyS3"; break;
                    case "4": path = "/dev/ttyS4"; break;
                    case "5": path = "/dev/ttyS5"; break;
                    case "6": path = "/dev/ttyS6"; break;
                    case "7": path = "/dev/ttyS7"; break;
                }
            }
            open(path);
        });

        binding.btClase.setOnClickListener(v -> onDestroy());
        binding.ivMessage.setOnClickListener(v -> finish());

        // 按键监听
        findViewById(R.id.btn_power).setOnClickListener(v -> {
            protocol.setCurrentKey(InductionCookerSerialSlave.KEY_POWER);
            appendToMonitor("设置按键: 电源");
        });

        findViewById(R.id.btn_timer).setOnClickListener(v -> {
            protocol.setCurrentKey(InductionCookerSerialSlave.KEY_TIMER);
            appendToMonitor("设置按键: 定时/预约");
        });

        findViewById(R.id.btn_decrease).setOnClickListener(v -> {
            protocol.setCurrentKey(InductionCookerSerialSlave.KEY_DECREASE);
            appendToMonitor("设置按键: 减");
        });

        findViewById(R.id.btn_increase).setOnClickListener(v -> {
            protocol.setCurrentKey(InductionCookerSerialSlave.KEY_INCREASE);
            appendToMonitor("设置按键: 加");
        });

        findViewById(R.id.btn_function).setOnClickListener(v -> {
            protocol.setCurrentKey(InductionCookerSerialSlave.KEY_FUNCTION);
            appendToMonitor("设置按键: 功能");
        });

        findViewById(R.id.btn_start).setOnClickListener(v -> {
            protocol.setCurrentKey(InductionCookerSerialSlave.KEY_START);
            appendToMonitor("设置按键: 启动");
        });
        binding.btnDisconnect.setEnabled(false);
    }



    boolean isOpen;
    private void open(String path) {
        appendToMonitor("开始连接串口设备: " + path);
        isOpen = protocol.connect(path);
        if (isOpen) {
            appendToMonitor("状态: 已连接");
            Toast.makeText(this, "状态: 已连接", Toast.LENGTH_SHORT).show();
        } else {
            appendToMonitor("串口打开失败");
        }
    }

    private void appendToMonitor(String message) {
        runOnUiThread(() -> {
            String time = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault()).format(new Date());
            String currentText = binding.tvMonitor.getText().toString();
            String newText = "[" + time + "] " + message + "\n" + currentText;

            // 限制显示行数
            if (newText.split("\n").length > 100) {
                newText = newText.substring(0, newText.lastIndexOf("\n", newText.lastIndexOf("\n") - 1));
            }
            binding.tvMonitor.setText(newText);
        });
    }

    // ============ 协议回调实现 ============ //
    @Override
    public void onDisplayUpdate(int thousands, int hundreds, int tens, int units, byte ledStatus) {
        runOnUiThread(() -> {
            binding.tvThousands.setText(String.valueOf(thousands));
            binding.tvHundreds.setText(String.valueOf(hundreds));
            binding.tvTens.setText(String.valueOf(tens));
            binding.tvUnits.setText(String.valueOf(units));
            updateLeds(ledStatus);
            appendToMonitor("显示更新: " + thousands + hundreds + tens + units);
        });
    }

    private void updateLeds(byte ledStatus) {
        int ledOn = Color.RED;
        int ledOff = Color.GRAY;

        leds[0].setColorFilter((ledStatus & InductionCookerSerialSlave.LED_FRYING) != 0 ? ledOn : ledOff);
        leds[1].setColorFilter((ledStatus & InductionCookerSerialSlave.LED_PORRIDGE) != 0 ? ledOn : ledOff);
        leds[2].setColorFilter((ledStatus & InductionCookerSerialSlave.LED_HOTPOT) != 0 ? ledOn : ledOff);
        leds[3].setColorFilter((ledStatus & InductionCookerSerialSlave.LED_HIGH_FIRE) != 0 ? ledOn : ledOff);
        leds[4].setColorFilter((ledStatus & InductionCookerSerialSlave.LED_LOW_FIRE) != 0 ? ledOn : ledOff);
        leds[5].setColorFilter((ledStatus & InductionCookerSerialSlave.LED_BOIL_WATER) != 0 ? ledOn : ledOff);
        leds[6].setColorFilter((ledStatus & InductionCookerSerialSlave.LED_STEAM) != 0 ? ledOn : ledOff);
        leds[7].setColorFilter((ledStatus & InductionCookerSerialSlave.LED_STEW) != 0 ? ledOn : ledOff);

        appendToMonitor("功能: " + InductionCookerSerialSlave.getActiveLeds(ledStatus));
    }

    @Override
    public void onKeySent(int keyCode) {
        runOnUiThread(() -> {
            String keyName = InductionCookerSerialSlave.getKeyName(keyCode);
            Toast.makeText(this, "已发送按键: " + keyName, Toast.LENGTH_SHORT).show();
            appendToMonitor("发送按键: " + keyName);
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onConnectionStatusChanged(boolean connected, String portPath) {
        runOnUiThread(() -> {
            if (connected) {
                binding.tvStatus.setText("已连接: " + portPath);
                appendToMonitor("已连接到串口: " + portPath);
            } else {
                binding.tvStatus.setText("已断开连接");
                appendToMonitor("连接已断开");
            }
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onError(String errorMessage) {
        runOnUiThread(() -> {
            binding.tvStatus.setText("错误: " + errorMessage);
            appendToMonitor("错误: " + errorMessage);
            Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
        });
    }

    @Override
    public void onDataReceived(byte[] data) {
        runOnUiThread(() -> {
            StringBuilder sb = new StringBuilder("接收数据: ");
            for (byte b : data) sb.append(String.format("0x%02X ", b));
            appendToMonitor(sb.toString());
        });
    }

    @Override
    public void onDataSent(byte[] data) {
        runOnUiThread(() -> {
            StringBuilder sb = new StringBuilder("发送数据: ");
            for (byte b : data) sb.append(String.format("0x%02X ", b));
            appendToMonitor(sb.toString());
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (protocol != null) protocol.disconnect();
        appendToMonitor("已断开连接");
    }
}